<?php
/**
 * --------------------------------------------------------------
 * 管理员模型
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\model;

use think\Model;

class Admin extends Model
{
    protected $autoWriteTimestamp = true;
    
    /**
     * 用户登录
     * @param string $adminname
     * @param string $password
     * @return boolean
     */
    public static function login($adminname = '', $password = '')
    {
        if (empty($adminname) || empty($password)) return -1;

        $ainfo = self::get(['adminname' => trim($adminname)]);
        if (empty($ainfo) || $ainfo->status !== 1) {
            return -1;
        }
        if (encrypt_password($password, $ainfo['encrypt']) !== $ainfo['password']) {
            return -2;
        }
        self::autoLogin($ainfo);

        return true;
    }

    /**
     * 自动登录
     * @param array $ainfo 用户信息
     */
    private static function autoLogin($ainfo)
    {
        self::loginStatus((int) $ainfo['id']);
        $auth = [
            'aid'             => $ainfo['id'],
            'adminname'       => $ainfo['adminname'],
            'nickname'        => $ainfo['nickname'],
            'avatar'          => $ainfo['avatar'],
            'last_login_time' => $ainfo['last_login_time'],
            'last_login_ip'   => get_client_ip(1)
        ];
        session('admin_auth', $auth);
        session('admin_auth_sign', data_auth_sign($auth));

        return $ainfo['id'];
    }
    
    /**
     * 后台检测用户是否登录
     */
    public static function isLogin()
    {
        $admin = session('admin_auth');
        if (empty($admin)) {
            return 0;
        } else {
            return session('admin_auth_sign') == data_auth_sign($admin) ? $admin['aid'] : 0;
        }
    }

    /**
     * 更新用户登录状态
     * @param integer $aid
     */
    private static function loginStatus($aid)
    {
        $data = [
            'last_login_time' => time(),
            'last_login_ip'   => get_client_ip(1)
        ];

        return self::where(['id' => $aid])->update($data);
    }
    
    /**
     * 获取用户信息
     * @param integer/string $identifier
     * @param string $password
     */
    public static function getUserInfo($identifier, $password = null)
    {
        if (empty($identifier)) return false;
        $map = [];
        if (is_int($identifier)) {
            $map['id'] = $identifier;
        } else {
            $map['adminname'] = $identifier;
        }
        $ainfo = self::where($map)->find();
        if (empty($ainfo)) return false;
        if (!empty($password) && encryptPassword($password, $ainfo['encrypt']) != $ainfo['password']) return false;
        return $ainfo;
    }
}